package com.terabits.smartriver.netty.config;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by Yin on 2019-04-01
 */
@Component
public class NettyServer {

    @Autowired
    private InitNetty initNetty;

    private NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    private NioEventLoopGroup workGroup = new NioEventLoopGroup();
    private ServerBootstrap serverBootstrap = new ServerBootstrap();

    @Autowired
    private ChildChannelInitializer childChannelInitializer;

    private Channel channel;

    public void start() {
        try {
            serverBootstrap
                    .group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, initNetty.isNodelay())
                    .option(ChannelOption.SO_BACKLOG, initNetty.getBacklog())
                    .childHandler(childChannelInitializer);
            channel = serverBootstrap.bind(initNetty.getPort()).addListener(future -> {
                if (future.isSuccess()) {
                    System.out.println("端口[" + initNetty.getPort() + "]绑定成功!");
                } else {
                    System.err.println("端口[" + initNetty.getPort() + "]绑定失败!");
                }
            }).sync().channel();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
//
    public void stop() throws Exception {
        channel.closeFuture().sync();
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
    }
}
